/**
 * Created by lee_mxue on 17/5/8.
 */
import React from "react";
import ReactDOM from "react-dom";
import AJAX from "../../lib/ajax";
import wx from "wx";
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare";
import CONFIG from "../../lib/config"
require('../../lib/rem');
require('./CabinetNearbyList.less');
require('../../styles/common.less');
require('../../styles/resetWeui.less');
require('../../styles/lux.less')
let MyCarousel = require('../../components/PictureSlick')
const Toast = require('../MyPackage/components/Toast')


class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isReady: false,     //页面是否加载
            cabinet_data: {
                count: 0,
                list: [],
            },   //柜体列表
            location_name: '',  //地理位置详细名称
            selectedCabinet: {},   //已选柜体信息
        };
        this.getLocation = this.getLocation.bind(this)  //获取地理位置，刷新附近柜体
        this.getCabinetList = this.getCabinetList.bind(this)  //获取柜体列表
        this.getLocationName = this.getLocationName.bind(this)  //获取地理位置详细名称
        this.handleChooseCabinet = this.handleChooseCabinet.bind(this)  //勾选柜体
    }

    componentWillMount() {
        var _this = this;
        addErrorListener()()
        //隐藏分享功能
        weixinShare.hideAll();
        //获取地理位置，刷新附近柜体
        if(CONFIG.dev_env) {
            this.TestgetLocation();
        }else {
            this.getLocation();
        }
    }

    // 测试环境模拟柜体位置
    TestgetLocation() {
        var latitude = 39.9837; // 纬度，浮点数，范围为90 ~ -90
        var longitude = 116.4858; // 经度，浮点数，范围为180 ~ -180。
        //获取柜体列表
        this.getCabinetList(latitude, longitude)
        //获取地理位置详细名称
        this.getLocationName(latitude, longitude)
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()

        var _this = this;
        //获取已选柜体信息
        if(window.localStorage.getItem('CabinetSendingInfo_x')){
            var CabinetSendingInfo_x = JSON.parse(window.localStorage.getItem('CabinetSendingInfo_x'));
            this.setState({
                selectedCabinet: CabinetSendingInfo_x
            })
        }
    }

    //组件卸载，解绑监听事件
    componentWillUnmount() {
        //阻止事件冒泡---解除监听
        var iconList = document.getElementsByClassName('icon') ? document.getElementsByClassName('icon') : [];
        for (var i = 0; i < iconList.length; i++) {
            iconList[i].removeEventListener('click', function (e) {
                //阻止默认事件，a标签跳转
                e.preventDefault();
                //显示选中状态
                e.target.setAttribute("class", "textBlue icon iconfont fontSize26px iconB icon-duigouzhuanhuan");
                window.location.href = './CabinetSendingHeader'
            }, false);
        }
    }

    //获取地理位置，刷新附近柜体
    getLocation() {
        var _this = this;
        //获取签名
        AJAX.request("get_signature", {
            full_url: window.location.href
        }, (data) => {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.body.appid, // 必填，公众号的唯一标识
                timestamp: data.body.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.body.noncestr, // 必填，生成签名的随机串
                signature: data.body.signature,// 必填，签名，见附录1
                jsApiList: ["getLocation"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            })
            wx.ready(()=> {
                //获取地理位置
                wx.getLocation({
                    type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                    success: function (res) {
                        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                        var speed = res.speed; // 速度，以米/每秒计
                        var accuracy = res.accuracy; // 位置精度
                        //获取柜体列表
                        _this.getCabinetList(latitude, longitude)
                        //获取地理位置详细名称
                        _this.getLocationName(latitude, longitude)

                    }
                });
            })
        })
    }

    //根据坐标获取位置名称
    getLocationName(latitude, longitude) {
        var _this = this;

        AJAX.request('get_by_location', {
            latitude: latitude, // 纬度，浮点数，范围为90 ~ -90
            longitude: longitude, // 经度，浮点数，范围为180 ~ -180。
        }, data => {
            _this.setState({
                location_name: data.body.address
            })
        })
    }

    //获取柜体列表
    getCabinetList(latitude, longitude) {
        var _this = this;
        //获取柜体列表
        AJAX.request('cabinet_list', {
            latitude: latitude, // 纬度，浮点数，范围为90 ~ -90
            // latitude: latitude || 39.98378, // 纬度，浮点数，范围为90 ~ -90
            longitude: longitude, // 经度，浮点数，范围为180 ~ -180。
            // longitude: longitude || 116.4856, // 经度，浮点数，范围为180 ~ -180。
        }, data => {
            let my_data = {
                count: data.body.count,
                list: data.body.list,
            }

            _this.setState({
                cabinet_data: my_data,
                isReady: true,  //页面是否加载
            })
            //阻止事件冒泡
            var iconList = document.getElementsByClassName('icon') ? document.getElementsByClassName('icon') : [];
            for (var i = 0; i < iconList.length; i++) {
                iconList[i].addEventListener('click', function (e) {
                    //阻止默认事件，a标签跳转
                    e.preventDefault();
                    //显示选中状态
                    // e.target.setAttribute("class", "textBlue icon iconfont fontSize26px iconB icon-duigouzhuanhuan");
                    //勾选柜体
                    //所选柜体信息
                    var cabinetInfo = e.target.getAttribute('data-cabinet');
                    _this.handleChooseCabinet(cabinetInfo);
                }, false);
            }

        })

    }

    //勾选柜体
    handleChooseCabinet(cabinetInfo) {
        var cabinet_info = JSON.parse(cabinetInfo)
        //将柜体信息存入LocalStorage
        var CabinetSendingInfo = {
            id: cabinet_info.id,
            name: cabinet_info.name,
            need_id_auth: cabinet_info.need_id_auth
        }
        window.localStorage.setItem('CabinetSendingInfo_x', JSON.stringify(CabinetSendingInfo));
        //跳转到柜体寄件首页
        window.location.href = './CabinetSendingHeader';
    }

    //toast弹窗
    warn(content) {
        Toast.warn({
            content: content
        })
    }

    success() {
        Toast.success({
            content: "成功"
        })
    }

    error() {
        Toast.error({
            content: "失败"
        })
    }

    loading(duration) {
        Toast.loading({
            content: "数据加载中",
            duration: duration,
        })
    }


    render() {
        var show = this.state.cabinet_data.count === 0 ?
            <img src="//cdn2.jinlb.cn/web/weixin/images/nocompany.png" alt=""/> : <div className="main">
            <div className=" top_active flex_row">
                <p className="of_scroll flex1 flex_row"><i
                    className="iconfont fontSize26px icon-dingwei"/>
                    <i className="flex1">
                        {this.state.location_name}
                    </i>
                </p>
                <i className="iconfont fontSize20px icon-iconfontshuaxin"
                   onClick={this.getLocation}/>
            </div>

            <div className="center_content">
                <div className="weui-cells">
                    {
                        this.state.cabinet_data.list.map((item, index) => {

                            return (
                                <a className={index == 0 ? "weui-cell weui-cell_access borderT borderB" : "weui-cell weui-cell_access borderB"}
                                   href={"./CabinetNearbyDetail?cabinet_id=" + item.id}>
                                    <div className="weui-cell__bd">
                                        <p>{item.name}</p>
                                        <p className="fontSize12px textGray">{item.addr}</p>
                                    </div>
                                    <div
                                        className="weui-cell__ft"><i
                                        className={item.id == this.state.selectedCabinet.id ? "icon textBlue iconfont fontSize26px iconB icon-duigouzhuanhuan" : "icon iconfont fontSize26px iconB icon-duigouzhuanhuan"}
                                        data-cabinet={JSON.stringify(item)}/>
                                    </div>
                                </a>
                            )
                        })
                    }
                </div>
            </div>
        </div>
        return (
            this.state.isReady && show

        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}